package org.hot100_1;

import org.leetcode.TreeNode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class leetcode45 {

    //层序遍历，遍历每一层结束时，会记录这一层的节点。只需统计这一层的最后一个节点即可。
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        checkFun(root,list);
        return list;
    }

    private void checkFun(TreeNode root,List<Integer> list){
        if (root==null){
            return;
        }

        Deque<TreeNode> deque = new LinkedList<>();
        deque.add(root);

        while (!deque.isEmpty()){
            int size = deque.size();
            List<Integer> layer = new ArrayList<>();
            while (size>0){
                TreeNode node = deque.poll();
                layer.add(node.val);

                if (node.left!=null){
                    deque.add(node.left);
                }
                if (node.right!=null){
                    deque.add(node.right);
                }
                size--;
            }
            list.add(layer.get(layer.size()-1));
        }
    }
}
